package bbs.intercepot;

import bbs.entity.config.AdminConfig;
import bbs.entity.constants.Constants;
import bbs.entity.dto.SessionAdminUserDto;
import bbs.entity.enums.ResponseCodeEnum;
import bbs.exception.BusinessException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component("appInterceptor")
public class AppInterceptor implements HandlerInterceptor {
    @Resource
    private AdminConfig adminConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        if (handler == null) return false;

        if (!(handler instanceof HandlerMethod)) return true;

        if (request.getRequestURL().indexOf("checkCode") != -1 || request.getRequestURL().indexOf("login") != -1) return true;

        checkLogin();
        return true;
    }

    private void checkLogin() {
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = httpServletRequest.getSession();
        SessionAdminUserDto sessionUserDto = (SessionAdminUserDto) session.getAttribute(Constants.SESSION_KEY);
        if (sessionUserDto == null && adminConfig.getIsDev()) {
            sessionUserDto = new SessionAdminUserDto();
            sessionUserDto.setAccount("管理员");
            session.setAttribute(Constants.SESSION_KEY, sessionUserDto);
        }
        if (sessionUserDto == null) throw new BusinessException(ResponseCodeEnum.CODE_901);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
